package org.zhq.client;

import org.zhq.box.StringReceivePacket;
import org.zhq.client.bean.ServerInfo;
import org.zhq.handle.ConnectorHandler;
import org.zhq.handle.ConnectorStringPacketChain;
import org.zhq.util.CloseUtils;

import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

/**
 * @author zhengquan
 * @date 2018/12/23
 */
public class TCPClient extends ConnectorHandler {

    public TCPClient(SocketChannel channel, File cachePath, boolean isNeedPrintReceiveString) throws IOException {
        super(channel, cachePath);
        if (isNeedPrintReceiveString) {
            getStringPacketChain().appendLast(new PrintStringPacketChain());
        }
    }

    private class PrintStringPacketChain extends ConnectorStringPacketChain {

        @Override
        protected boolean consume(ConnectorHandler handler, StringReceivePacket stringReceivePacket) {
            String string = stringReceivePacket.entity();
            System.out.println(string);
            return true;
        }
    }

    public static TCPClient startWith(ServerInfo info, File cachePath) throws IOException {
        return startWith(info,cachePath,true);
    }


    public static TCPClient startWith(ServerInfo info, File cachePath, boolean isNeedPrintReceiveString) throws IOException {

        SocketChannel channel = SocketChannel.open();
        //连接服务器;超时时间3000ms
        channel.connect(new InetSocketAddress(Inet4Address.getByName(info.getAddress()), info.getPort()));

        System.out.println("已发起服务器连接,并进入后续流程!");
        System.out.println("客户端信息:" + channel.getLocalAddress().toString());
        System.out.println("服务器信息:" + channel.getRemoteAddress().toString());

        try {
            return new TCPClient(channel, cachePath, isNeedPrintReceiveString);
        } catch (Exception e) {
            System.out.println("连接异常");
            CloseUtils.close(channel);
        }

        return null;
    }
}
